const R = require('ramda')
const Schema = require('async-validator').default
const getFirstErrorMessage = R.compose(
  R.prop('message'),
  R.head,
  R.prop('errors')
)

const validation = R.curry((descriptor, data) => {
  const validator = new Schema(descriptor)
  return new Promise((resolve, reject) => {
    return validator
      .validate(data)
      .then(resolve)
      .catch((e) => {
        const message = getFirstErrorMessage(e)
        reject(new Error(message))
      })
  })
})

module.exports = validation
